package foundation.tree.binaryTree;

import java.util.*;

/**
 * @author hang an
 * @since 2025/7/11
 */
public class 层序遍历 {
    public static void main(String[] args) {

    }


    public List<List<Integer>> bfs(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        Map<TreeNode, Integer> levels = new HashMap<>();
        levels.put(root, 0);
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            Integer curLevel = levels.get(node);
            if (curLevel == ans.size()) {
                ans.add(new ArrayList<>());
            }
            ans.get(curLevel).add(node.val);
            if (node.left != null) {
                levels.put(node.left, curLevel + 1);
                queue.add(node.left);
            }
            if (node.right != null) {
                levels.put(node.right, curLevel + 1);
                queue.add(node.right);
            }
        }
        return ans;
    }

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ans = new ArrayList<>();
        if (root == null) return ans;
        dfs(root, 0, ans);
        return ans;
    }

    public void dfs(TreeNode root, int deep, List<List<Integer>> ans) {
        if (root == null) return;
        if (deep == ans.size()) {
            ans.add(new ArrayList<>());
        }
        ans.get(deep).add(root.val);
        if (root.left != null) {
            dfs(root.left, deep + 1, ans);
        }
        if (root.right != null) {
            dfs(root.right, deep + 1, ans);
        }
    }

}
